#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File Name: N_m3u8DL-RE_batch.py
# Author: bobo
# Created Time: 20231224
"""
批量下载m3u8脚本
"""
import os
import sys


def dlm3u8(outfile, url):
    """
    下载m3u8
    """
    cmd = "N_m3u8DL-RE"
    print(f'{cmd} --save-name "{outfile}" "{url}"')
    os.system(f'{cmd} --save-name "{outfile}" "{url}"')


def batch_dl(filename):
    """
    批量下载m3u8
    """
    if os.path.isfile(filename):
        # 文件，格式要求:  文件名,m3u8 url
        m3u8_urls = []
        with open(filename, "r", encoding="utf-8") as fh:
            lines = fh.readlines()
            m3u8_urls = [
                line.strip().split(",") for line in lines
                if not line.startswith("#") and line.strip()
            ]
            m3u8_urls = [config for config in m3u8_urls if len(config) == 2]
        for file, url in m3u8_urls:
            # 2024.8.6 add
            if os.path.exists(file + ".mp4"):
                print(file, ".mp4 exists.")
                continue
            dlm3u8(file, url)
    else:
        print(f"文件不存在：{filename}")


if __name__ == "__main__":
    try:
        params = len(sys.argv)
        if params == 2:
            batch_dl(sys.argv[1])
        elif params == 3:
            dlm3u8(sys.argv[1], sys.argv[2])
        else:
            print("用法: ./.N_m3u8DL-RE_batch.py <file>|<outfile m3u8_url>")
            sys.exit()
    except Exception as e:
        print(f"错误：{e}")
